package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.CheckGroup;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = com.itheima.service.CheckGroupService.class)
public class CheckGroupServiceImpl implements com.itheima.service.CheckGroupService {

    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkGroupMapper.addCheckGroup(checkGroup);//mybatis会自动封装自增长的id进入bean对象
        addGroupAndItem(checkGroup.getId(),checkitemIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupMapper.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Integer> findCheckItemId(Integer id) {

        return checkGroupMapper.findCheckItemId(id);
    }

    @Override
    public CheckGroup findCheckGroupById(Integer id) {
        return checkGroupMapper.findCheckGroupById(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkItemIdS) {
        //先对checkgroup表进行更新操作,再对关联表进行更新操作
        checkGroupMapper.update(checkGroup);
        //根据id查询关联表,再进行更新操作,这样有点麻烦,直接删除关联表相关数据,再进行更新操作
        checkGroupMapper.delete(checkGroup.getId());
        addGroupAndItem(checkGroup.getId(),checkItemIdS);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();
    }

    public void addGroupAndItem(Integer id,Integer[] checkitemIds){
        if (checkitemIds != null && checkitemIds.length > 0){//说明此事检查项的选择非空
            //遍历该数组,并将此时的检查组id和检查项的id封装成map集合,添加到二者关联表中
            for (Integer checkitemId : checkitemIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("checkgroup_id",id);
                map.put("checkitem_id",checkitemId);
                checkGroupMapper.addGroupAndItem(map);
            }
        }
    }
}
